﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Action.Entity;
using T.FAS.Runtime.Action.SPI;

namespace T.FAS.Runtime.Action.Dao
{
    public class MSS_DBInfoViewDao: AbsDBInfoViewDao
    {
        public override DataBaseInfoView GetDataBaseInfoViewByDataBaseCode(DataBaseInfo info)
        {
            var result = new DataBaseInfoView()
            {
                ID = info.Code+info.DBType,
                Code = info.Code,
                Name = info.Code,
                Description = info.Code,
                Details = new List<DataBaseItemView>()
            };
            var db = GetDatabaseByConfigkey(info.ConnectionKey);

            //获取数据库的表+字段信息
            var tableSql = "select name as TableName from sysobjects where xtype='u' ORDER BY name";
            var tableResult = db.ExecuteDataSet(tableSql);
            var tableItemViews = ConvertToItems(tableResult, DataBaseItemType.Table);
            tableItemViews.ForEach(t =>
            {
                var colSql = $"SELECT COLUMN_NAME as ColumnName,DATA_TYPE as DataType from information_schema.columns where table_name='{t.Code}' ORDER BY ordinal_position";
                var colResult = db.ExecuteDataSet(colSql);
                var colItemViews = ConvertToColumnItems(colResult);
                t.Details = colItemViews;
            });
            result.Details.AddRange(tableItemViews);

            //获取数据库的视图+字段信息
            var viewSql = "select name as TableName from sysobjects where xtype='v' ORDER BY name";
            var viewResult = db.ExecuteDataSet(viewSql);
            var viewItemViews = ConvertToItems(viewResult, DataBaseItemType.View);
            viewItemViews.ForEach(t =>
            {
                var colSql = $"SELECT COLUMN_NAME as ColumnName,DATA_TYPE as DataType from information_schema.columns where table_name='{t.Code}' ORDER BY ordinal_position";
                var colResult = db.ExecuteDataSet(colSql);
                var colItemViews = ConvertToColumnItems(colResult);
                t.Details = colItemViews;
            });
            result.Details.AddRange(viewItemViews);

            //获取数据库的存储过程信息
            var procSql = "select name as TableName from sysobjects where xtype='p' ORDER BY name";
            var procResult = db.ExecuteDataSet(procSql);
            var procItemViews = ConvertToItems(procResult, DataBaseItemType.Procedure);
            result.Details.AddRange(procItemViews);

            return result;
        }
    }
}
